package com.canbot.u05.service;

import android.app.IntentService;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.Nullable;

import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.update.CheckVersion;
import com.canbot.u05.update.ConstUtils;
import com.canbot.u05.update.FileUtils;
import com.canbot.u05.update.RobotUtil;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.coolerfall.download.DownloadCallback;
import com.coolerfall.download.DownloadManager;
import com.coolerfall.download.DownloadRequest;
import com.coolerfall.download.OkHttpDownloader;
import com.coolerfall.download.Priority;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 版本更新服务
 * Created by xh on 2017/7/1.
 */

public class VersionUpdateService extends IntentService {

        private static final String TAG = "VersionUpdateService";

        private ArrayList<CheckVersion> checkVersions;

        private String packageNames = "";

        private String vscode = "";

        /**
         * Creates an IntentService.  Invoked by your subclass's constructor.
         */
        public VersionUpdateService() {
                super(TAG);
        }

        @Override
        protected void onHandleIntent(@Nullable Intent intent) {

                Logger.e(TAG, "VersionUpdateService start");

                checkVersion();
        }

        /**
         * 读取version文件的信息
         */
        private void readVersion() {
                File a = new File(ConstUtils.PATH_VERSION);
                if (a.exists()) {
                        try {
                                BufferedReader br = new BufferedReader(new FileReader(a));
                                vscode = br.readLine();
                                br.close();
                        }
                        catch (IOException e) {
                                e.printStackTrace();
                        }
                }
        }

        public void checkVersion() {
                readVersion();
                FileUtils.deleteFile(ConstUtils.PATH_UPDATE_APK);

                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("", "");

//                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "allversionservlet", hasMap, new OkHttpUtils.OkHttpCallBack() {
//
//                        @Override
//                        public void onSuccess(String result) {
//                                Logger.e(TAG, "onSuccess versionInfo = " + result);
//                                checkVersions = (ArrayList<CheckVersion>) JSON.parseArray(result, CheckVersion.class);
//                                if (checkVersions != null && checkVersions.size() > 0) {
//                                        compareVersion();
//                                }
//                        }
//
//                        @Override
//                        public void onFailure() {
//                                Logger.e(TAG, "check version onFailure");
//                        }
//                });
        }

        /**
         * 比较版本号
         */
        private void compareVersion() {
                packageNames = "";
                String aiString = "";
                for (int i = 0, size = checkVersions.size(); i < size; i++) {
                        try {
                                if (checkVersions.get(i).getVersioncode() == null || checkVersions.get(i).getVersioncode().trim().equals("0")) {
                                        continue;
                                }
                                if (checkVersions.get(i).getPackagename().equalsIgnoreCase("ai_version")) {
                                        if (vscode != null && !vscode.isEmpty() && !vscode.equals("")) {
                                                int mversion = Integer.parseInt(vscode.trim());
                                                int version = Integer.parseInt(checkVersions.get(0).getVersioncode().trim());
                                                Logger.d(TAG, "local_ai_version =" + mversion + "  :: service_version=" + version);
                                                if (("" + version).compareTo("" + mversion) > 0) {// ai的版本号低于服务器的
                                                        aiString = ":" + checkVersions.get(i).getPackagename().trim() + (":" + mversion);
                                                }
                                        }
                                        else {
                                                aiString = ":" + checkVersions.get(i).getPackagename().trim() + (":" + 0);// ai的版本加"222"标志
                                        }
                                        continue;
                                }

                                if (!RobotUtil.isPkgInstalled(this, checkVersions.get(i).getPackagename().trim(), TAG)) {// apk是否已安装
                                        packageNames = packageNames + (":" + checkVersions.get(i).getPackagename().trim());
                                        continue;
                                }
                                // 系统已经安装的apk的版本号.
                                int mversion = getPackageManager().getPackageInfo(checkVersions.get(i).getPackagename().trim(), 0).versionCode;
                                // 服务器的版本号.
                                int version = Integer.parseInt(checkVersions.get(i).getVersioncode().trim());
                                if (("" + version).compareTo("" + mversion) > 0) {
                                        String name = checkVersions.get(i).getPackagename().trim();
                                        packageNames = packageNames + (":" + name);

                                }
                                Logger.e(TAG, "local_ " + checkVersions.get(i).getPackagename().trim() + "_version =" + mversion + "  :: service_version=" + version);

                        }
                        catch (PackageManager.NameNotFoundException e) {
                                e.printStackTrace();
                        }

                }

                if (!aiString.equals("")) {
                        packageNames = aiString + packageNames;
                }

                if (packageNames != null && packageNames.contains(":")) {
                        packageNames = packageNames.substring(1);
                        getDownloadUrl();
                        Logger.e(TAG, "packageNames=" + packageNames);
                }
        }

        public void getDownloadUrl() {
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("packagename", packageNames);
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "someversionservlet", hasMap, new OkHttpUtils.OkHttpCallBack() {

                        @Override
                        public void onSuccess(String result) {
                                Logger.e(TAG, "onSuccess downloadUrl = " + result);
                                downloadApk(result);
                        }

                        @Override
                        public void onFailure() {
                                Logger.e(TAG, "getDownloadUrl onFailure");
                        }
                });
        }

        public void downloadApk(String url) {
                if (url.isEmpty() || !url.endsWith(".apk")) {
                        return;
                }
                File file = new File(ConstUtils.PATH_UPDATE_APK);
                if (!file.exists()) {
                        file.mkdirs();
                }
                String name = url.substring(url.lastIndexOf("/") + 1);
                String destPath = ConstUtils.PATH_UPDATE_APK + name;
                final String downloadUrl = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + url;
                DownloadRequest request = new DownloadRequest.Builder().url(downloadUrl).retryTime(1).retryInterval(1, TimeUnit.SECONDS).progressInterval
                        (1, TimeUnit.SECONDS).priority(Priority.HIGH).allowedNetworkTypes(DownloadRequest.NETWORK_WIFI).destinationFilePath(destPath)
                        .downloadCallback(new DownloadCallback() {
                                @Override
                                public void onStart(int downloadId, long totalBytes) {
                                        Logger.e(TAG, "start download " + downloadUrl);
                                }

                                @Override
                                public void onRetry(int downloadId) {
                                }

                                @Override
                                public void onProgress(int downloadId, long bytesWritten, long totalBytes) {
                                        //                showProgress((int) (bytesWritten * 100 / totalBytes));
                                }

                                @Override
                                public void onSuccess(int downloadId, String filePath) {
                                        Logger.e(TAG, "download succeed " + filePath);
                                        RobotUtil.install(new File(filePath), VersionUpdateService.this);
                                }

                                @Override
                                public void onFailure(int downloadId, int statusCode, String errMsg) {
                                        Logger.e(TAG, "downloadApk failed " + errMsg);
                                }
                        }).build();
                new DownloadManager.Builder().context(VersionUpdateService.this).downloader(OkHttpDownloader.create()).threadPoolSize(2).build().add
                        (request);
        }

}
